<?php
session_start();
global $amount, $category, $paypal;
$do_payment = FALSE;
if(isset($_REQUEST['paytype'])){
    // Check paypal :)
    // Create instance of the phpPayPal class
    $paypal = new phpPayPal($privates, $privates['API_SANDBOX']);
    $paypal->ip_address = $_SERVER['REMOTE_ADDR'];
	$do_payment = TRUE;
}
if(isset($_REQUEST['cancel'])){
	$do_payment = FALSE;
}
if ($do_payment && $_REQUEST['paytype'] != 3) {

    // (required)

    // Order Totals (amount_total is required)
    $_SESSION['amount'] = $paypal->amount_total = $_REQUEST["amount"];
    $paypal->amount_shipping = '0';

    // Credit Card Information (required)
    $paypal->credit_card_number = $_REQUEST["cardNumber"];
    $paypal->credit_card_type = $_REQUEST["cardType"];
    $paypal->cvv2_code = $_REQUEST["cardSecurityNumber"];
    //$paypal->expire_date = '112008';
    $paypal->expire_date = $_REQUEST["month"] . $_REQUEST["year"];

    // Billing Details (required)
    $paypal->email = $_REQUEST["email"];

    // Add Order Items (NOT required) - Name, Number, Qty, Tax, Amt
    // Repeat for each item needing to be added
    $_SESSION['category'] = $_REQUEST["category"];
    $paypal->add_item($_SESSION["category"], $_SESSION["category"], 1, 0, $_SESSION["amount"]);

    if ($_REQUEST['paytype'] == 1) {
        $paypal->return_url = $privates['API_RETURN_URL'] . "&paytype=0";
        $paypal->cancel_url = $privates['API_CANCEL_URL'] . "&paytype=0";
        // Billing Details (required)
        $paypal->first_name = $_REQUEST["firstname"];
        $paypal->last_name = $_REQUEST["lastname"];
        $paypal->address1 = $_REQUEST["address"];
        $paypal->city = $_REQUEST["city"];
        $paypal->state = $_REQUEST["state"];
        $paypal->postal_code = $_REQUEST["zip"];
        $paypal->phone_number = $_REQUEST["phone"];
        $paypal->country_code = 'US';

        // Perform the payment
        $paypal->do_direct_payment();
    }
}

if ($do_payment && $_REQUEST['paytype'] == 2) {
    $paypal->return_url = $privates['API_RETURN_URL'] . "paytype=3";
    $paypal->cancel_url = $privates['API_CANCEL_URL'] . "paytype=3";
    // Make the request
    $paypal->set_express_checkout();

    // Now go to PayPal
    $paypal->set_express_checkout_successful_redirect();
}
// finish express payment 
if ($do_payment && $_REQUEST['paytype'] == 3 && isset($_REQUEST['token']) && isset($_REQUEST['PayerID'])) {
    // Final total amount and shipping
    $paypal->amount_total = $_SESSION['amount'];
    $paypal->amount_shipping = '0';

    // Add items to the PayPal transaction (not required)
    // addItem() function FORMAT - $name, $number, $quantity, $amount_tax, $amount
    $paypal->add_item($_SESSION['category'], $_SESSION['category'], 1, 0, $_SESSION['amount']);

    $paypal->token = $_REQUEST['token'];
    $paypal->payer_id = $_REQUEST['PayerID'];
    $paypal->do_express_checkout_payment();
}
if ($do_payment && $_REQUEST['paytype'] == 3 && isset($_REQUEST['token']) && !isset($_REQUEST['PayerID'])) {
    // Final total amount and shipping
    $paypal->_error = TRUE;
    $paypal->_error_long_message = "Missing Payment ID";
}
if($do_payment){
   // print_r($paypal->Response['ACK']);
//    print_r($paypal->_error_short_message);
//    print_r($paypal->_error_long_message);
}

























/*if (0) {
    $MSG = "";
    switch ($SUBMIT) {
        case 'Submit Payment':

            // Create Payment record for the transaction
            if ($PAYID == "") {
                $q = "INSERT newPay";
                $q .= " (transDate,edProcess) "; // first field, regID is blank for add
                $q .= " valueS ( ";
                $q .= "'$dt', "; //transDate == Date
                $q .= "'1') "; //edProcess: 1 = initial create
                if ($DEBUG)
                    echo "BEGIN:: $q<BR>";
                $db->query($q);
                $status = $db->next_record();
                if ($DEBUG)
                    echo "INSERT status=[$status]<BR>\n";
                // Verify add worked
                if (!$status) {
                    $MSG = "Add Ok";
                    // What payID was created 
                    // set $PAYID so that update will work on it
                    $q = "SELECT payID, transDate";
                    $q .= "  FROM newPay ";
                    $q .= " WHERE transDate='" . $dt . "' ";
                    if ($DEBUG)
                        echo "VERIFY:: $q<BR>";
                    $db->query($q);
                    $status = $db->next_record();
                    $PAYID = $db->f("payID");
                    if ($DEBUG)
                        echo "PAYID:: $PAYID<BR>";
                }
            }
            $cardExpiration = $_REQUEST["month"] . "/" . $_REQUEST["year"];
            // now that it is created - update/reSubmits work great!
            $q = "UPDATE newPay ";
            $q .= " SET ";
            $q .= " edProcess='2', "; //edProcess: 2 = updated
            $q .= " category='" . $_REQUEST["category"] . "', ";
            $q .= " email='" . $_REQUEST["email"] . "', ";
            $q .= " website='" . $_REQUEST["website"] . "', ";
            $q .= " authTransactionID='', "; //authorize.net transaction type
            $q .= " invoiceNumber='" . $_REQUEST["invoiceNumber"] . "', ";
            $q .= " description='" . $_REQUEST["description"] . "', ";
            $q .= " cardName='" . $_REQUEST["cardName"] . "', ";
            $q .= " cardType='" . $_REQUEST["cardType"] . "', ";
            $q .= " cardNumber='" . $_REQUEST["cardNumber"] . "', ";
            $q .= " cardExpiration='" . $cardExpiration . "', ";
            $q .= " amount='" . $_REQUEST["amount"] . "' ";
            $q .= " WHERE payID='$PAYID' ";

            if ($DEBUG)
                echo "UPDATE:: $q<BR>";

            $db->query($q);

            $status = $db->next_record();

            //Process with authorize.net        
            if ($DEBUG)
                echo "authMessage = $authMessage<BR>\n";

            //Verify confirmation
            if ($auth_return[0] == 1) {  //authorization success
                //Update record
                $q = "UPDATE newPay";
                $q .= "   SET ";
                $q .= " cardNumber='" . asterisk_pad($_REQUEST["cardNumber"], 4) . "', ";
                $q .= " authCode ='$auth_return[4]', ";
                $q .= " edProcess = 3, ";
                $q .= " authTransactionID ='$auth_return[37]', ";
                $q .= " transType ='$auth_return[11]' ";
                $q .= " WHERE payID=$PAYID";
                if ($DEBUG)
                    echo "UPDATE:: $q<BR>";

                $db->query($q);
                $status = $db->next_record();
                $emailTo = "support@epiphanydev.com";
                // Verify update worked
                if ($status) {
                    //email record info for support, customer does not need to know.
                    $emailSubject = "need help ==>EDI online payment=$PAYID";
                    $emailBody = "They did the data entry for us!\n";
                    $emailBody.="BUT I failed to update the record????\n";
                    $emailBody.="Please process the following update manually.\n";
                    $emailBody.="$q";
                    $emailHeader = "";
                    //two more arguments exist: headers and parameters see php mail docs
                    mail($emailTo, $emailSubject, $emailBody, "From: support@epiphanyDev.com\r\n");
                    // display done
                    echo "\n<HTML><BODY>";
                    echo "\n<meta http-equiv=refresh content=\"0;
                    url=done.php?payID=$PAYID\">";
                    echo "\n</BODY></HTML>";
                    exit();
                } else {
                    // email record info for accounting, customer does not need to know.
                    // errEmail demonstrates how we monitor errors for our customers.
                    //$errEmailTo="support@epiphanydev.com";
                    $emailSubject = "EDI online payment=$PAYID";
                    $emailBody = "They did the data entry for us!\n";
                    $emailBody.="Payment ID = $PAYID, AMOUNT = " . $_REQUEST["amount"];
                    $emailHeader = "";
                    mail($emailTo, $emailSubject, $emailBody, "From: support@epiphanyDev.com\r\n");
                    //mb_send_mail($errEmailTo, $emailSubject, $emailBody, "From: contact@h-m-c.com\r\n");
                    // display done
                    echo "\n<HTML><BODY>";
                    echo "\n<meta http-equiv=refresh content=\"0;
                    url=done.php?payID=$PAYID\">";
                    echo "\n</BODY></HTML>";
                    exit();
                }
            } else {
                //Auth failed
                //Nothing to do here - message displays in html and user is ready to correct and resubmit
            }
    }// end switch
}
?>
*/